package org.springframework.security.samples.interceptor;

import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.samples.web.MainController;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class AccessIntercetor extends HandlerInterceptorAdapter{
	
	private static Log LOG = LogFactory.getLog(MainController.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
		String url = request.getRequestURL().toString();
		LOG.info("url: " + url);
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Set<String> userRoles =  authentication.getAuthorities().stream().map(role -> role.getAuthority()).collect(Collectors.toSet());
		LOG.info("userRoles: " + userRoles);
		if(url.contains("/checker")){
			if(!userRoles.contains("ROLE_CHECKER")){
				throw new AccessException("You don't have access to this function! Please contact your admin.");
			}
		}
		return true;
	}
}
